package com.hh.vietnameseproject.ui.search

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.hh.vietnameseproject.R
import com.hh.vietnameseproject.databinding.ActivitySearchBinding
import com.hh.vietnameseproject.logic.network.AllNetWork
import com.hh.vietnameseproject.ui.login.ActivityController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject

class SearchActivity : AppCompatActivity() {
    lateinit var binding:ActivitySearchBinding

    var type = "auto2vi"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ActivityController.addList(this)
        binding.searchActivityBackBtn.setOnClickListener {
            onBackPressed()
        }
        binding.translateBtn.setOnClickListener {
            val et = binding.searchEdit.text.toString().trim()
            binding.textOld.text = et
            GlobalScope.launch {
                val body = AllNetWork.translate(type,et)
                val jsonObject = JSONObject(body.string())
                withContext(Dispatchers.Main) {
                    if (jsonObject.getInt("code")==1){
                        binding.textNew.text = jsonObject.getJSONObject("data").getString("百度翻译")
                    }
                }
            }
        }

        binding.radipGroup.setOnCheckedChangeListener { radioGroup, i ->
            type = if(i == R.id.radio1) "auto2vi" else  "1"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityController.removeList(this)
    }
}